package com.jic.manager.controller.manage.memstorecontroller;

import com.jic.common.base.vo.Page;
import com.jic.common.base.vo.PageResult;
import com.jic.common.base.vo.RestResult;
import com.jic.common.redis.RedisClientTemplate;
import com.jic.conf.api.manage.SysConfigApi;
import com.jic.conf.request.SysConfigRequest;
import com.jic.conf.response.SysConfigResponse;
import com.jic.manager.common.util.BeanUtil;
import com.jic.manager.controller.manage.conf.SysConfigController;
import com.jic.manager.entity.Mestore;
import com.jic.manager.entity.SysDept;
import com.jic.manager.entity.SysRoleUser;
import com.jic.manager.entity.SysUser;
import com.jic.manager.enums.DeptTypeEnum;
import com.jic.manager.request.MestoreRequest;
import com.jic.manager.request.StoreListGetReuqest;
import com.jic.manager.response.MemStoreResponse;
import com.jic.manager.response.MestoreResponse;
import com.jic.manager.service.MerchantService;
import com.jic.manager.service.MestoreService;
import com.jic.manager.service.SysDeptService;
import com.jic.manager.service.SysRoleUserService;
import com.jic.manager.service.SysUserService;
import com.jic.product.after.api.ProductListApi;
import com.jic.product.after.request.SaveProductRequest;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 店铺信息维护
 *
 * @autho wwb
 */
@RestController
@RequestMapping("/store")
public class MemStoreController {
    @Resource
    private MestoreService memStoreService;
    @Resource
    public RedisClientTemplate redisClientTemplate;
    @Resource
    ProductListApi productListApi;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysDeptService sysDeptService;
    @Resource
    private MerchantService merchantService;
    @Resource
    private SysConfigApi sysConfigApi;
    @Resource
    private SysRoleUserService sysRoleUserService;



    //查询店铺列表
    @RequestMapping(value = "/findStorePageInfo")
    public RestResult<PageResult<MemStoreResponse>> findStorePageInfo(@RequestBody MestoreRequest form) {
        MestoreRequest mestoreRequest = new MestoreRequest();
        BeanUtils.copyProperties(form, mestoreRequest);
        PageResult<MemStoreResponse> mestorePageResult = new PageResult<>();
        if (form.getStart() != null && form.getLimit() != null){
            mestorePageResult = memStoreService.queryPage(mestoreRequest, new Page() {{
                setStart(form.getStart());
                setLimit(form.getLimit());
            }});
        }else{
            Mestore mestore = new Mestore();
            BeanUtils.copyProperties(mestoreRequest,mestore);
            List<Mestore> query = memStoreService.query(mestore);
            List<MemStoreResponse>  res = new ArrayList<>();
            for (Mestore me : query) {
                MemStoreResponse memStoreResponse = new MemStoreResponse();
                BeanUtils.copyProperties(me,memStoreResponse);
                res.add(memStoreResponse);
            }
            mestorePageResult.setRows(res);
        }

        return RestResult.success(mestorePageResult);
    }


    /*
     * 查询单个店铺对象
     * */
    @ApiOperation(value = "查询单个店铺对象")
    @ResponseBody
    @RequestMapping("/getStoreInfo")
    public RestResult<MestoreResponse> getStoreInfo(@RequestBody MestoreRequest mestoreRequest) {

        MestoreResponse storeVo1 = memStoreService.getStoreInfo(mestoreRequest);
        return RestResult.success(storeVo1);
    }


//    //根据商家id集合查询店铺
//    @PostMapping(value = "/queryByIds")
//    public RestResult<PageResult<MestoreResponse>> queryByIds(@RequestBody MestoreRequest mestoreRequest) {
//        try {
//            List<MestoreResponse> memStoreList = new ArrayList<>();
//            String merchantIds = mestoreRequest.getMerchantIds();
//            if (StringUtils.isEmpty(merchantIds)) {
//                throw new Exception("查询店铺失败! 必传参数ids为空");
//            }
//            mestoreRequest.setDeleteFlag("N");
//            PageResult<MestoreResponse> res = new PageResult<>();
//            if (mestoreRequest.getStart() == null && mestoreRequest.getLimit() == null) {
//
//                res = memStoreService.queryStoreInfoPage(mestoreRequest, new Page() {{
//                    setStart(1);
//                    setLimit(10);
//                }});
//            }else {
//                res = memStoreService.queryStoreInfoPage(mestoreRequest, new Page() {{
//                    setStart(mestoreRequest.getStart());
//                    setLimit(mestoreRequest.getLimit());
//                }});
//            }
//            List<MestoreResponse> rows = res.getRows();
//            memStoreList.addAll(rows);
//            List list = memStoreList.stream().map(e -> {
//                e.setStoreName(e.getStoreName());
//                e.setStoreCode(e.getStoreCode());
//                return e;
//            }).collect(Collectors.toList());
//            res.setRows(list);
//            return RestResult.success(res);
//        } catch (Exception e) {
//            // TODO
//            e.printStackTrace();
//            return RestResult.error("9999", e.getLocalizedMessage());
//        }
//    }

    /***
     * 根据商家编码集合查询店铺
     * @param mestoreRequest
     * @return
     */
    @PostMapping(value = "/queryByOrgNumber")
    public RestResult<PageResult<MestoreResponse>> queryByOrgNumber(@RequestBody MestoreRequest mestoreRequest) {
        try {
            List<MestoreResponse> memStoreList = new ArrayList<>();
            String merchantIds = mestoreRequest.getDeptIds();
            if (StringUtils.isEmpty(merchantIds)) {
                throw new Exception("查询店铺失败! 必传参数ids为空");
            }
            mestoreRequest.setDeleteFlag("N");
            PageResult<MestoreResponse> res = memStoreService.queryStoreInfoPageByOrgNumber(mestoreRequest, new Page() {{
                setStart(mestoreRequest.getStart());
                setLimit(mestoreRequest.getLimit());
            }});
            List<MestoreResponse> rows = res.getRows();
            memStoreList.addAll(rows);
            List list = memStoreList.stream().map(e -> {
                e.setStoreName(e.getStoreName());
                e.setStoreCode(e.getStoreCode());
                return e;
            }).collect(Collectors.toList());
            res.setRows(list);
            return RestResult.success(res);
        } catch (Exception e) {
            // TODO
            e.printStackTrace();
            return RestResult.error("9999", e.getLocalizedMessage());
        }
    }


    // 修改编辑店铺
    @PostMapping(value = "/editStoreInfo")
    public RestResult<String> editStoreInfo(@RequestBody MestoreRequest mestoreRequest) {
        RestResult result =new RestResult();
        if (StringUtils.isNotEmpty(String.valueOf(mestoreRequest.getIsAccept()))&&"1".equals(String.valueOf(mestoreRequest.getIsAccept()))) {//如果是调用接口
            SaveProductRequest productInfoRequest = new SaveProductRequest();
            productInfoRequest.setDeptId(mestoreRequest.getDeptId());
            productInfoRequest.setStoreId(mestoreRequest.getId());
            productListApi.saveStoreProduct(productInfoRequest);
        }
        result= memStoreService.editStoreInfo(mestoreRequest);
     return  result;
    }



    // 批量审核
    @PostMapping(value = "/checkStoreStatus")
    public RestResult<String> reviewStoreStatus(@RequestBody MestoreRequest mestoreRequest) throws Exception {
        RestResult result = new RestResult();
        try {
            String ids = mestoreRequest.getIds();
            Long reviewStatus = mestoreRequest.getReviewStatus();
            String[] idList = ids.split(",");
            if (reviewStatus == 2) {
                //审核拒绝
                if (StringUtils.isEmpty(mestoreRequest.getReviewReason())) {
                    return RestResult.error("9999", "审核拒绝需填写拒绝原因，请填写拒绝原因");
                }
            }
            //查询conf配置
            RestResult<List<SysConfigResponse>> infoByKey = sysConfigApi.getInfoByKey(new SysConfigRequest() {{
                setIds("302");
            }});
            List<SysConfigResponse> configList = infoByKey.getData();
            SysConfigResponse baseStoreInfo = configList.stream().filter(config -> config.getId() == 302L).collect(Collectors.toList()).get(0);
            for (int i = 0; i < idList.length; i++) {
                Long id = Long.valueOf(idList[i]);

                Mestore mestore = memStoreService.queryByPrimaryKey(id);
                List<SysDept> deptList = sysDeptService.query(new SysDept() {{
                    setBusinessId(mestore.getMerchantId());
                    setDeptType(DeptTypeEnum.MERCHANT_TYPE.getType());
                }});

                Long deptId = null;

                if (reviewStatus == 1L){
                    //审核成功 增加组织架构
                    deptId = sysDeptService.insertSysDept(new SysDept(){{
                        setDeptName(mestore.getStoreName());
                        setPid(deptList.get(0).getId());
                        setBusinessId(mestore.getId());
                        setDeptType(DeptTypeEnum.STORE_TYPE.getType());
                        setStatus("0");
                        setCreateTime(new Date());
                        setCreator(mestoreRequest.getAdminOperate().getOperator());
                        setDeleteFlag(0);
                    }});
                }
                Long finalDeptId = deptId;
                SysUser sysUser = sysUserService.queryByPrimaryKey(mestore.getUserId());
                if (sysUser == null || sysUser.getDeleteFlag().equals(1)) {
                    throw new Exception("当前店铺不存在账号");
                }
                sysUserService.update(new SysUser(){{
                    setRoleid(sysUser.getRoleid() != null ? sysUser.getRoleid() : Long.valueOf(baseStoreInfo.getVal()));
                    setLname(finalDeptId != null ? mestore.getStoreName() : null);
                    setDeptId(finalDeptId);
                    setId(sysUser.getId());
                    setUpdateTime(new Date());
                    if (reviewStatus == 1L){
                        setStatus(1);
                    }else{
                        setStatus(0);
                    }
                }});
                memStoreService.update(new Mestore() {{
                    setId(id);
                    setDeptId(finalDeptId);
                    setReviewStatus(reviewStatus);
                    if (reviewStatus == 2) {
                        setReviewReason(mestoreRequest.getReviewReason());
                    }
                    setUpdateTime(new Date());
                }});

                sysRoleUserService.insert(new SysRoleUser(){{
                    setStatus("0");
                    setRoleid(Long.valueOf(baseStoreInfo.getVal()));
                    setUserid(sysUser.getId());
                }});
            }
        } catch (Exception e) {

            return RestResult.error("9999",e.getLocalizedMessage());
        }
        return RestResult.success("0000");
    }


    // 根据商家id集合查询店铺-加数据权限控制修正
    @PostMapping(value = "/queryByIds")
    public RestResult<PageResult<MestoreResponse>> getByMerchantIdS(@RequestBody StoreListGetReuqest storeListGetReuqest){

        return  memStoreService.getByMercrchantIds(storeListGetReuqest);
    }

    //查询列表
    @PostMapping(value = "/queryStoreList")
    public RestResult<List<MestoreResponse>> queryStoreList(@RequestBody MestoreRequest mestoreRequest){
        List<MestoreResponse> mStoreResponseList=new ArrayList<>();
        if(CollectionUtils.isNotEmpty(mestoreRequest.getAdminOperate().getDeptIds())){
            List<Mestore> mestoreList  = memStoreService.queryStoreList(mestoreRequest);
            if(CollectionUtils.isNotEmpty(mestoreList)){
                mestoreList.forEach(item->{
                    MestoreResponse mestoreResponse=new MestoreResponse();
                    BeanUtil.copy(item,mestoreResponse);
                    mStoreResponseList.add(mestoreResponse);
                });
            }
        }
        return RestResult.success(mStoreResponseList);
    }


    @ApiOperation(value = "查询店铺列表不要分页")
    @PostMapping(value = "findByIds")
    @ResponseBody
    public RestResult<PageResult<MestoreResponse>> findByIds(@RequestBody StoreListGetReuqest storeListGetReuqest){

        return  memStoreService.findByIds(storeListGetReuqest);
    }


}
